package models

import (
	"gitee.com/lzqysoft/framework/common/log"

	"gitee.com/lzqysoft/framework/common/encrypt"

	csql "gitee.com/lzqysoft/framework/services/base/sql"

	"gitee.com/lzqysoft/framework/common/tool"
	"gitee.com/lzqysoft/framework/common/uuid"
	"github.com/go-xorm/xorm"
	"github.com/kataras/iris/core/errors"
	"time"
)

var db *xorm.Engine

func init() {
	engine, _ := csql.GetConn()
	db = engine
}

type User struct {
	Id         string `xorm:"not null pk index unique VARCHAR(64)"`
	Onwer      string `xorm:"VARCHAR(64)"`
	Group      string `xorm:"VARCHAR(64)"`
	Creater    string `xorm:"VARCHAR(64)"`
	CreateAt   int64  `xorm:"BIGINT"`
	CreateOrg  string `xorm:"VARCHAR(64)"`
	Updater    string `xorm:"VARCHAR(64)"`
	UpdateAt   int64  `xorm:"BIGINT"`
	Deleter    string `xorm:"VARCHAR(64)"`
	DeleteAt   int64  `xorm:"BIGINT"`
	Isdelete   string `xorm:"VARCHAR(2)"`
	Status     string `xorm:"VARCHAR(2)"`
	Remark     string `xorm:"VARCHAR(255)"`
	Operation  int    `xorm:"INTEGER"`
	Obligate3  string `xorm:"VARCHAR(64)"`
	Obligate2  string `xorm:"VARCHAR(64)"`
	Obligate   string `xorm:"VARCHAR(64)"`
	Account    string `xorm:"VARCHAR(32)"`
	AccountKey string `xorm:"VARCHAR(255)"`
	OldKey     string `xorm:"VARCHAR(255)"`
	LoginTime  int64  `xorm:"BIGINT"`
	LoginIp    string `xorm:"VARCHAR(64)"`
	OrganId    string `xorm:"VARCHAR(64)"`
}

func (v *User) TableName() string {
	return "base_user"
}

func (v *User) BeforeInsert() {
	v.Id = uuid.UUID()
	v.CreateAt = time.Now().Unix()
	v.UpdateAt = time.Now().Unix()
}

func (v User) Convert2Map() map[string]interface{} {
	return tool.Struct2Map(v)
}

//CheckLogin 录验证,用户名、密码，返回user和error
func CheckLogin(uname string, pwd string) (user *User, err error) {
	user, err = GetUserByUname(uname)
	if err != nil {
		return nil, errors.New("没有此用户")
	}
	log.Debug(pwd)
	log.Debug(encrypt.EncodeUserPwd(user.Account, pwd))
	if encrypt.EncodeUserPwd(user.Account, pwd) != user.AccountKey {
		return nil, errors.New("密码不正确！")
	}
	return user, nil
}

func GetUserByUname(uname string) (user *User, err error) {

	user = &User{Account: uname}
	has, err := db.Get(user)
	if !has {
		return nil, errors.New("no record")
	}
	return
}

// GetUserNameExist 查询用户帐号是否存在
func GetUserNameExist(uname string) bool {
	user := User{Account: uname}
	has, err := db.Exist(&user)
	if err != nil || !has {
		return false
	}
	return true
}

func GetUserById(id string) (*User, error) {
	user := &User{Id: id}
	has, err := db.Get(user)
	if !has {
		return nil, errors.New("no record")
	}
	if err != nil {
		return nil, err
	}
	return user, nil
}

func AddUser(user *User) error {
	session := db.NewSession()
	defer session.Close()
	session.Begin()

	if _,err := session.Insert(user); err != nil {
		session.Rollback()
		return err
	}

	profile := &Profile{UserId:user.Id}
	if  _, err := session.Insert(profile); err != nil {
		session.Rollback()
		return err
	}
	session.Commit()
	return nil
}
